var CTX = $.app.basePath;
var themeKey = 'superTheme';
var _updatePassword = CTX + '/sys/user/updatePassword';
var _getCurrentUser = CTX + '/getUserInfo';

var $mainTabs = null;
var onlyOpenTitle = "欢迎使用";// 不允许关闭的标签的标题

$(function () {
    setTheme(localStorage.getItem(themeKey));

    $mainTabs = $('#mainTabs');

    $('#loading-mask').fadeOut();

    // 初始化左侧菜单
    initLeftMenu();

    $mainTabs.tabs({
        tools: [{
            iconCls: 'fa fa-refresh',
            border: false,
            handler: function () {
                $('#mm-tabupdate').trigger("click");
            }
        }]
    });

    /* 设置按钮的下拉菜单 */
    $('.super-setting-icon').on('click', function () {
        $('#setting-mm').menu('show', {
            top: 52,
            left: document.body.scrollWidth - 130
        });
    });

    /* 修改密码 */
    $('#editpass').click(function () {
        $('#pwd-fm').form('clear');
        $('#pwd-dlg').dialog('open');
    });

    /* 修改主题 */
    $('#themeSetting').on('click', function () {
        var $themeWin = $('#win');
        $themeWin.dialog({
            modal: true,
            title: '主题设置',
            buttons: [{
                text: '保存',
                id: 'btn-sure',
                handler: function () {
                    $themeWin.panel('close');
                    var theme = $('.themeItem .themeActive>div').attr('class');
                    setTheme(theme);
                    localStorage.setItem(themeKey, theme);
                }
            }, {
                text: '关闭',
                handler: function () {
                    $themeWin.panel('close');
                }
            }],
            onOpen: function () {
                $(".themeItem").show();
            }
        });
    });

    $(".themeItem ul li").on('click', function () {
        $(".themeItem ul li").removeClass('themeActive');
        $(this).addClass('themeActive');
    });

    /* 退出系统 */
    $('#logout').click(function () {
        $.messager.confirm('系统提示', '您确定要退出本次登录吗?', function (r) {
            if (r) {
                window.location.href = CTX + '/logout';
            }
        });
    });

    // 绑定tab双击关闭事件 和 右键上下文
    bindTabCloseEvent();

    // 绑定右键菜单
    bindRightMenuEvent();

});

// 修改主题
function setTheme (themeName) {
    themeName = themeName || 'superYellow';

    var $themeCss = $('#themeCss');
    var themeUrl = $themeCss.attr('href').split('/');
    themeUrl.pop();
    $themeCss.attr('href', themeUrl.join('/') + '/' + themeName + '.css');

    // 添加勾选状态
    $(".themeItem ul li").removeClass('themeActive');
    $('.themeItem ul li .' + themeName).parent().addClass('themeActive');
}

function seeUserInfo() {
    $.get(_getCurrentUser, function (data) {
        var $dlg = $('#user-info-dlg');
        $dlg.find('form').form('load', data.data);
        $dlg.dialog({
            modal: true,
            buttons: [{
                text: '关闭',
                iconCls: 'fa fa-close',
                plain: true,
                handler: function () {
                    $dlg.dialog('close');
                }
            }]
        }).dialog('open');
    });
}

function createIFrame(url) {
    if (!/^http/.test(url) && !new RegExp('^' + CTX).test(url)) {
        url = CTX + url;
    }
    url = encodeURI(url);
    return '<iframe name="Iframe" scrolling="auto" frameborder="0"  src="' + url + '" width="100%" height="99%"></iframe>';
}

/**
 * 初始化左侧菜单
 */
function initLeftMenu() {
    $.getJSON(CTX + '/app/menu.json', function (data) {
        builtMenu(data);
    });
}

function initLeftMenu() {
    $.ajax({
        type: 'get',
        url: CTX + '/findMenuByUser',
        dataType: 'json',
        success: function (data, textStatus, jqXHR) {
            data = $.dataFilter(data);
            if (data) {
                var changeData = changeMenuList(data);
                builtMenu(changeData);
            }
        }
    });
}

function changeMenuList(list) {
    var temp = [];
    $.each(list, function (i, o) {
        if (o.type === 0 || o.type === 1) {
            var n = {
                menuid: o.id,
                icon: o.icon || "fa fa-bars",
                menuname: o.name,
                url: o.url
            };
            if (o.children && o.children.length > 0) {
                n.children = changeMenuList(o.children);
            }
            temp.push(n);
        }
    });
    return temp;
}

/**
 * 添加tab
 * @param title 标题
 * @param href 路径
 * @param iconCls 图标
 * @param isPanel 链接跳转方式（true为panel，false为iframe）
 */
function addTab(title, href, iconCls, isPanel) {

    if (!$mainTabs.tabs('exists', title)) {
        href = (href.indexOf('http') === 0 || href.indexOf(CTX) === 0) ? href : CTX + href;
        href = encodeURI(href);
        var opts = isPanel ? {
            title: title,
            href: href,
            iconCls: iconCls,
            fit: true,
            cls: 'pd3',
            closable: true
        } : {
            title: title,
            content: createIFrame(href),
            iconCls: iconCls,
            fit: true,
            cls: 'pd3',
            closable: true
        };

        if (iconCls === 'undefined' || !iconCls)
            delete opts.iconCls;

        $mainTabs.tabs('add', opts);
    } else {
        // 选中
        $mainTabs.tabs('select', title);
    }
}

/**
 * 关闭当前tab或指定title的tab
 */
function closeTab(title) {
    if (title !== onlyOpenTitle) {
        $mainTabs.tabs('close', title);
    } else {
        $.messager.alert('提示', '[' + onlyOpenTitle + ']不可以被关闭！', 'error');
    }
}

/**
 * 刷新当前tab
 */
function reloadCurrTab() {
    var currTab = $mainTabs.tabs('getSelected');
    var url = $(currTab.panel('options').content).attr('src');
    $mainTabs.tabs('update', {
        tab: currTab,
        options: {
            content: createIFrame(url)
        }
    });
}

/**
 * 绑定双击关闭TAB选项卡事件和右键菜单
 */
function bindTabCloseEvent() {
    var $mainTabs = $('#mainTabs');
    /* 双击关闭TAB选项卡 */
    $mainTabs.on('dblclick', '.tabs-inner', function () {
        var subtitle = $(this).children(".tabs-title").text();
        closeTab(subtitle);
    });

    /* 为选项卡绑定右键 */
    $mainTabs.on('contextmenu', '.tabs-inner', function (e) {
        var subtitle = $(this).children(".tabs-title").text();
        $('#mm').menu('show', {
            left: e.pageX,
            top: e.pageY
        })
        // 保存当前选项卡的title
        .data("currtab", subtitle);
        $mainTabs.tabs('select', subtitle);
        return false;
    });
}

/**
 * 绑定右键菜单
 *
 * @returns
 */
function bindRightMenuEvent() {
    // 刷新
    $('#mm-tabupdate').click(function () {
        reloadCurrTab();
    });

    // 关闭当前
    $('#mm-tabclose').click(function () {
        var currtab_title = $('#mm').data("currtab");
        closeTab(currtab_title);
    });

    // 全部关闭
    $('#mm-tabcloseall').click(function () {
        $('.tabs-inner span').each(function (i, n) {
            var title = $(n).text();
            closeTab(title);
        });
    });

    // 关闭当前右侧的TAB
    $('#mm-tabcloseright').click(function () {
        var nextall = $('.tabs-selected').nextAll();
        if (nextall.length === 0) {
            // alert('后边没有啦~~');
            return false;
        }
        nextall.each(function (i, n) {
            var t = $('a:eq(0) span', $(n)).text();
            closeTab(t);
        });
        return false;
    });

    // 关闭当前左侧的TAB
    $('#mm-tabcloseleft').click(function () {
        var prevall = $('.tabs-selected').prevAll();
        if (prevall.length === 0) {
            // alert('到头了，前边没有啦~~');
            return false;
        }
        prevall.each(function (i, n) {
            var t = $('a:eq(0) span', $(n)).text();
            closeTab(t);
        });
        return false;
    });

    // 关闭除当前之外的TAB
    $('#mm-tabcloseother').click(function () {
        $('#mm-tabcloseright').trigger('click');
        $('#mm-tabcloseleft').trigger('click');
    });

    // 退出
    $("#mm-exit").click(function () {
        $('#mm').menu('hide');
    });
}

/**
 * 构建菜单
 *
 * @param menus []
 */
function builtMenu(menus) {
    var $menu = $('#menu');

    $menu.accordion({
        fit: true,
        border: false,
        animate: false
    });

    $.each(menus, function (i, obj) {
        var menuHtml = '<ul class="navlist">';
        if (obj.children) {
            $.each(obj.children, function (j, o) {
                menuHtml += '<li><div ><a id="' + o.menuid + '" href="javascript:void(0);" rel="' + o.url + '" ><i class="' + o.icon + '" >&nbsp;</i><span class="nav">' + o.menuname + '</span>';
                if (o.children && o.children.length > 0) {
                    menuHtml += '&nbsp;&nbsp;<i class="fa fa-chevron-circle-down"></i>';
                }
                menuHtml += '</a></div>';
                if (o.children && o.children.length > 0) {
                    menuHtml += '<ul class="third_ul">';
                    $.each(o.children, function (k, p) {
                        menuHtml += '<li><div><a id="' + p.menuid + '" href="javascript:void(0);" rel="' + p.url + '" ><i class="' + p.icon + '" >&nbsp;</i><span class="nav">' + p.menuname
                            + '</span></a></div></li>';
                    });
                    menuHtml += '</ul>';
                }
                menuHtml += '</li>';
            });
        }
        menuHtml += '</ul>';

        $menu.accordion('add', {
            title: obj.menuname,
            content: menuHtml,
            iconCls: obj.icon
        });
    });

    // 选中第一个
    $menu.accordion({
        animate: true
    });

    // 绑定事件
    $('.navlist li a').click(function () {

        var tabTitle = $(this).children('.nav').text();

        var url = $(this).attr("rel");
        var menuid = $(this).attr("id");
        var icon = $(this).find('i').attr('class');

        var third = find(menuid, menus);
        if (third && third.children && third.children.length > 0) {
            $('.third_ul').slideUp();

            var ul = $(this).parent().next();
            var arrow = $($(this).find("i")[1]);
            if (ul.is(":hidden")) {
                // 打开
                ul.slideDown();
                $(".navlist").find('i.fa-chevron-circle-right').removeClass().addClass("fa fa-chevron-circle-down");
                arrow.removeClass().addClass("fa fa-chevron-circle-right");
            } else {
                // 收起
                ul.slideUp();
                arrow.removeClass().addClass("fa fa-chevron-circle-down");
            }

        } else {
            addTab(tabTitle, url, icon, false);
            $('.navlist li div').removeClass("selected");
            $(this).parent().addClass("selected");
        }
    }).hover(function () {
        $(this).parent().addClass("hover");
    }, function () {
        $(this).parent().removeClass("hover");
    });
}

/**
 * 获取三级菜单
 *
 * @param menuid
 * @param menus
 * @returns
 */
function find(menuid, menus) {
    var obj = null;
    $.each(menus, function (i, n) {
        if (n.children) {
            $.each(n.children, function (j, o) {
                if (o.menuid === menuid) {
                    obj = o;
                }
            });
        }
    });
    return obj;
}

/**
 * 修改密码
 */
function updatePassword() {
    $('#pwd-fm').submitEForm(_updatePassword, function () {
        $('#pwd-dlg').dialog('close');// close the dialog
    });
}
